/**
 * @Title: HomeActivity.java
 * @Package com.sinoglobal.waitingMe.activity
 * @Description: TODO(用一句话描述该文件做什么)
 * @author hpq
 * @date 2015-8-30 上午11:55:09
 */

package com.sinoglobal.wallet.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sinoglobal.wallet.R;
import com.sinoglobal.wallet.activity.W_SinoBaseActivity.DialogOnClickListener;
import com.sinoglobal.wallet.adapter.W_BankNameListAdapter;
import com.sinoglobal.wallet.api.RemoteImpl;
import com.sinoglobal.wallet.app.SinoConstans;
import com.sinoglobal.wallet.entity.W_DynamicKeyEntity;
import com.sinoglobal.wallet.entity.W_MyBankVo;
import com.sinoglobal.wallet.entity.W_RsListVo;
import com.sinoglobal.wallet.entity.W_VerifyPassNumVo;
import com.sinoglobal.wallet.entity.W_WithdrawalSuccessEntity;
import com.sinoglobal.wallet.entity.W_WithdrawlInstrutionEntiy;
import com.sinoglobal.wallet.task.MyAsyncTask;
import com.sinoglobal.wallet.util.LogUtils;
import com.sinoglobal.wallet.util.NetWorkUtil;
import com.sinoglobal.wallet.util.ValidUtil;
import com.sinoglobal.wallet.widget.KeyboardUtil;

/**
 * @author clf
 * @createdate 2015-10-22
 * @Description: TODO(余额明细)
 */
public class W_WithDrawalActivity extends W_SinoBaseActivity {
	private static final String TAG = W_WithDrawalActivity.class.getSimpleName();
	private TextView withDrawal_commmit, withDrawal_bank_name;
	public View view1;
	private RelativeLayout withDrawal_bank_layout, add_bank_card_layout;
	private int payState = 0;// 支付方式标识
	private PopupWindow mpopupWindow;
	private LinearLayout withdrawal_bank_popu;
	private AnimationSet outAnimationSet;
	private EditText withDrawal_num;

	private String str;// 金额数目
	private ListView withdrawl_bank_listview;
	private ArrayList<W_MyBankVo> list = new ArrayList<W_MyBankVo>();
	private W_BankNameListAdapter bankNameListAdapter;
	private InputMethodManager imm;
	private String userbcid = "";
	private Context context;
	private String isHaspass;
	private double blanceTxt;
	private boolean isSelectBank = false;
	private KeyboardUtil keyUtil;
	 private ChangeisPassReciver  changeisPassReciver;

	private int errCount=0;
	private TextView withDrawal_txTemplate1_txt,withDrawal_txTemplate2_txt,withDrawal_txTemplate3_txt;
	private String highestAmount="5000";//最高提现金额是5000.网络获取最高金额值
	private String chargeAmount="1";//手续费默认是1元.请求获取手续费显示;app端用来判断。具体余额扣除是后台服务器做处理
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.wallet_withdrawal_layout);
		context = this;
		mTemplateTitleText.setText("提现");
		showView(mTemplateRightText);
		mTemplateRightText.setText("记录");
		mTemplateRightText.setOnClickListener(this);
		if (getIntent() != null) {
			isHaspass = getIntent().getStringExtra("IsHasPass");
			blanceTxt = getIntent().getDoubleExtra("BlanceTxt", 0.0);
		}
		initView();
		initpopView();
		getBankList();
		initReciver();
		getWithDrawlInstrution() ;
	}
	 
									
	private void initView() {
		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		withDrawal_num = (EditText) findViewById(R.id.withDrawal_num);
		withDrawal_num.setHint("最多提出" + blanceTxt );
		keyUtil = new KeyboardUtil(context, withDrawal_num, true);
		keyUtil.disableShowSoftInput(withDrawal_num);
		withDrawal_num.setOnTouchListener(new OnTouchListener() {

			@SuppressLint("ClickableViewAccessibility")
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				keyUtil.showKeyboard();
				return false;
			}
		});

		withDrawal_bank_layout = (RelativeLayout) findViewById(R.id.withDrawal_bank_layout);
		withDrawal_bank_name = (TextView) findViewById(R.id.withDrawal_bank_name);
		withDrawal_txTemplate1_txt= (TextView) findViewById(R.id.withDrawal_txTemplate1_txt);
		withDrawal_txTemplate2_txt = (TextView) findViewById(R.id.withDrawal_txTemplate2_txt);
		withDrawal_txTemplate3_txt = (TextView) findViewById(R.id.withDrawal_txTemplate3_txt);
		withDrawal_bank_layout.setOnClickListener(this);
		withDrawal_commmit = (TextView) findViewById(R.id.withDrawal_commmit);
		withDrawal_commmit.setOnClickListener(this);
		withDrawal_num.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				str=s.toString().trim();
				if(str.indexOf(".") != -1){  
		             //获取小数点的位置  
		             int num = 0;  
		             num = str.indexOf(".");  
		               
		             //获取小数点后面的数字 是否有两位 不足两位补足两位  
		             String dianAfter = str.substring(0,num+1);  
		             String afterData = str.replace(dianAfter, "");  
		            if(afterData.length()>=3){
		            	String  data=str.substring(0,num) + "." + afterData.substring(0,2);
		            	withDrawal_num.setText(data)  ; 
		            	withDrawal_num.setSelection(data.length());}
			}
			}
		});	
	}
	/**
	 * 注册改变当前体现页面改变isHaspass值的广播
	 */
	private void initReciver() {
		// TODO Auto-generated method stub
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction("com.sinoglobal.wallet.receiver.withdrawal");
		changeisPassReciver = new ChangeisPassReciver();
		registerReceiver(changeisPassReciver, intentFilter);
	}
	/**
	 * 初始化popwindow
	 */
	public void initpopView() {
		// popwindow相关控件的初始化
		bankNameListAdapter = new W_BankNameListAdapter(this);
		view1 = View.inflate(this, R.layout.wallet_bank_popu_list_layout, null);
		withdrawal_bank_popu = (LinearLayout) view1.findViewById(R.id.withdrawal_bank_popu);
		add_bank_card_layout = (RelativeLayout) view1.findViewById(R.id.add_bank_card_layout);
		withdrawl_bank_listview = (ListView) view1.findViewById(R.id.withdrawl_bank_listview);
		
		bankNameListAdapter.setListData(list);
		add_bank_card_layout.setOnClickListener(this);
		withdrawl_bank_listview.setOnItemClickListener(new OnItemClickListener() {
			private Object item;

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				isSelectBank = true;
				popuDismiss();
				for (int i = 0; i < list.size(); i++) {
					list.get(i).setIsShow(false);
				}
				LogUtils.v("onItemClick______position" + position);
				item = bankNameListAdapter.getItem(position);
				if (item instanceof W_MyBankVo) {
					((W_MyBankVo) item).setIsShow(true);

				}
				withDrawal_bank_name.setText(list.get(position).getBankName()+ " (尾号"+ list.get(position).getCardSn().substring(list.get(position).getCardSn().toCharArray().length - 4,
										list.get(position).getCardSn().toCharArray().length) + ")");
				userbcid = list.get(position).getUserbcid();
				bankNameListAdapter.notifyDataSetChanged();

			}

		});
		view1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				popuDismiss();
			}
		});

		if (mpopupWindow == null) {
			mpopupWindow = new PopupWindow(this);
			mpopupWindow.setWidth(LayoutParams.MATCH_PARENT);
			mpopupWindow.setHeight(LayoutParams.WRAP_CONTENT);
			mpopupWindow.setBackgroundDrawable(new BitmapDrawable());
			mpopupWindow.setFocusable(true);
			mpopupWindow.setOutsideTouchable(true);
		}
		mpopupWindow.setContentView(view1);
	}

	private void mesureParams() {
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int mScreenWidth = dm.widthPixels;
		LayoutParams params = withdrawl_bank_listview.getLayoutParams();
		
		if (bankNameListAdapter == null) {
			return;
		}
		params.width = mScreenWidth;
		View listItem = bankNameListAdapter.getView(0, null, withdrawl_bank_listview);
		listItem.measure(0, 0);
		int itemHeight = listItem.getMeasuredHeight();
		if (list.size()<5) {
			params.height =itemHeight*list.size()+ (withdrawl_bank_listview.getDividerHeight() * (bankNameListAdapter.getCount() - 1));  
		}else{
			params.height = itemHeight*5+ (withdrawl_bank_listview.getDividerHeight() * 4);
		}
		withdrawl_bank_listview.setLayoutParams(params);
		
	}
	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.withDrawal_commmit) {
			str = withDrawal_num.getText().toString();
			Log.d(TAG, "str:" + str);
			if (!ValidUtil.validNumber(str).equals("")) {
				Toast.makeText(this, ValidUtil.validNumber(str), 0).show();
				return;
			}
			if (Double.valueOf(str) > Double.valueOf(highestAmount)) {
				showDialog(W_WithDrawalActivity.this, "提示", "单笔提现金额限"+highestAmount+"，请重新输入金额", "", R.color.w_c7, "", R.color.w_c14, false,
						new DialogOnClickListener() {

							@Override
							public void onSure(View v) {
							}

							@Override
							public void onCancle(View v) {
							}
						});
				return;
			}
			if (Double.valueOf(str) > blanceTxt) {
				showDialog(W_WithDrawalActivity.this, "提示", "输入的金额已超出余额数", "", R.color.w_c7, "", R.color.w_c14, false,
						new DialogOnClickListener() {

							@Override
							public void onSure(View v) {
							}

							@Override
							public void onCancle(View v) {
							}
						});
				return;
			}
			if (Double.valueOf(str) <=Double.valueOf(chargeAmount)) {
				Toast.makeText(this, "提现金额不得低于"+chargeAmount+"元哦！", 0).show();
				return;
			}
			if (isHaspass.equals("N")) {
				showToast("请先设置支付密码");
				Bundle setting_bundle = new Bundle();
				setting_bundle.putString("title_flag", "3");
				goIntent(W_PayPasswordActivity.class, setting_bundle);//设置密码
				return;
			}
			if (!isSelectBank) {
				showToast("请选择银行卡");
				return;
			}

			getUnPassWordNum();

		} else if (id == R.id.withDrawal_bank_layout) {
			keyUtil.hideKeyboard();
			imm.hideSoftInputFromWindow(withDrawal_num.getApplicationWindowToken(), 0);
			withdrawal_bank_popu.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.w_push_bottom_in));
			mpopupWindow.showAtLocation(withDrawal_bank_name, Gravity.BOTTOM, 0, 0);
			mpopupWindow.update();
			if (list.size() == 0) {
				Toast.makeText(W_WithDrawalActivity.this, "请绑定银行卡再提现", Toast.LENGTH_SHORT).show();
			}
		} else if (id == R.id.add_bank_card_layout) {
			Intent intent = new Intent(this, W_MyAddbankActivity.class);
			startActivityForResult(intent, 200);
		} else if (id == R.id.wallet_title_right_tv) {
			Bundle setting_bundle = new Bundle();
			setting_bundle.putString("instrution", withDrawal_txTemplate3_txt.getText().toString());
			goIntent(W_WithDrawalRecordActivity.class, setting_bundle);//设置密码
		} else if (id == R.id.wallet_noData) {
			 if(NetWorkUtil.getNetWorkInfoType(getApplicationContext())==NetWorkUtil.NONE){
					showToast("请检查网络是否连接！");	
					 loadError(true);
					}else{
						loadError(false);;
					}
		}
	}

	private void popuDismiss() {
		Animation Animation = AnimationUtils.loadAnimation(this, R.anim.w_push_bottom_out);
		withdrawal_bank_popu.startAnimation(Animation);
		Animation.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
				
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
				
			}

			@Override
			public void onAnimationEnd(Animation animation) {
				LogUtils.v("dismiss--------------");
				mpopupWindow.dismiss();
			}
		});
	}

	// 获取银行卡列表
	private void getBankList() {
		MyAsyncTask<W_RsListVo> task = new MyAsyncTask<W_RsListVo>(true, this, true) {

			@Override
			public W_RsListVo before(Void... params) throws Exception {
				// TODO 测试接口
				return RemoteImpl.getInstance().getBankList(W_WithDrawalActivity.this);
			}

			@Override
			public void after(W_RsListVo result) {

				if (result.getCode().equals("100")) {
					if (result.getRs().size() == 0) {
						list = (ArrayList<W_MyBankVo>) result.getRs();
					} else {
						list = (ArrayList<W_MyBankVo>) result.getRs();
						for (int i = 0; i < list.size(); i++) {
							list.get(i).setIsShow(false);
						}
						withdrawl_bank_listview.setAdapter(bankNameListAdapter);
						bankNameListAdapter.setListData(list);
						mesureParams() ;
						sendBroadcast(list.size());
					}
				} else {
					showToast(result.getMsg());
				}

			}

			@Override
			public void exception() {
			}
		};
		task.execute();
	}
	private void sendBroadcast(int str) {
		Intent intent = new Intent();
		intent.setAction(SinoConstans.KEY_BalanceReceiver);
		intent.putExtra("bankCardNum", str+"");
		sendBroadcast(intent);
	}
	//获取提现金额的说明
	private void getWithDrawlInstrution() {
		MyAsyncTask<W_WithdrawlInstrutionEntiy> task = new MyAsyncTask<W_WithdrawlInstrutionEntiy>(false, this, true) {
			@Override
			public W_WithdrawlInstrutionEntiy before(Void... params) throws Exception {
				// TODO 测试接口
				return RemoteImpl.getInstance().getWithDrawlInstrution();
			}
			@Override
			public void after(W_WithdrawlInstrutionEntiy result) {
				if (result.getCode().equals("100")) {
					
					withDrawal_txTemplate1_txt.setText(result.getRs().getTxTemplate1());
					withDrawal_txTemplate2_txt.setText(result.getRs().getTxTemplate2());
					withDrawal_txTemplate3_txt.setText(result.getRs().getTxTemplate3());
					highestAmount = result.getRs().getHighestAmount();
					 chargeAmount = result.getRs().getChargeAmount();
          }
			}
			@Override
			public void exception() {
			}
		};
		task.execute();
	}
	// 获取动态秘钥
		private void getDynamicKey( final String password) {
			MyAsyncTask<W_DynamicKeyEntity> task = new MyAsyncTask<W_DynamicKeyEntity>(true, this, true) {
				@Override
				public W_DynamicKeyEntity before(Void... params) throws Exception {
					// TODO 测试接口
					return RemoteImpl.getInstance().getDynamicKey();
				}
				@Override
				public void after(W_DynamicKeyEntity result) {
					 String id="";//
					 String encryptKey="";//动态秘钥
                    id = result.getId();
                    encryptKey = result.getEncryptKey();
            	getWithDrawal(password,id,encryptKey);
				}
				@Override
				public void exception() {
				}
			};
			task.execute();
		}
	// 获取密码错误次数
		private void getUnPassWordNum() {
			MyAsyncTask<W_VerifyPassNumVo> task = new MyAsyncTask<W_VerifyPassNumVo>(true, this, true) {

				@Override
				public W_VerifyPassNumVo before(Void... params) throws Exception {
					// TODO 测试接口
					return RemoteImpl.getInstance().getUnPassWordNum(W_WithDrawalActivity.this);
				}

				@Override
				public void after(W_VerifyPassNumVo result) {

					if (result.getCode().equals("100")) {
						errCount = result.getErrCount();
						if(errCount<5){
						Intent intent = new Intent(W_WithDrawalActivity.this, W_OrderPayActivity.class);
						Bundle bundle = new Bundle();
						bundle.putString("Money", str);
						bundle.putString("Type", "WD");// 提现页面传来的标示
						intent.putExtras(bundle);
						startActivity(intent);
						}else{
							showDialog(W_WithDrawalActivity.this, "提示", "您今日密码输入次数超限，密码被锁定，请于2小时候后再尝试", "返回", R.color.w_c7, "", R.color.w_c14, false,
									new DialogOnClickListener() {

										@Override
										public void onSure(View v) {
											
										}

										@Override
										public void onCancle(View v) {
										}
									});
						}
					} else {
						showToast(result.getDescription());
					}

				}

				@Override
				public void exception() {
				}
			};
			task.execute();
		}
	// 提现请求
	private void getWithDrawal(final String password, final String id, final String encryptKey) {
		MyAsyncTask<W_WithdrawalSuccessEntity> task = new MyAsyncTask<W_WithdrawalSuccessEntity>(true, this, true) {

			@Override
			public W_WithdrawalSuccessEntity before(Void... params) throws Exception {
				// TODO 测试接口
				return RemoteImpl.getInstance().getTiXian(W_WithDrawalActivity.this, password, str, getSystemTime(), "1", "1", userbcid, "0",id,encryptKey);
			}

			@Override
			public void after(W_WithdrawalSuccessEntity result) {
           if(result!=null){
				if (result.getCode().equals("100")) {
					showMidToast("提现成功");
					sendBroadcast(result.getRs().getBalance());
					Bundle bundle = new Bundle();
					bundle.putString("BankName", withDrawal_bank_name.getText().toString());
					bundle.putString("Money", str);
					bundle.putString("fees", result.getRs().getFees());
					bundle.putString("Instrution", withDrawal_txTemplate3_txt.getText().toString());
					goIntent(W_WithDrawalDetailActivity.class, bundle);
					finish();
				}else if(result.getCode().equals("101")){
					if(result.getRs().getResult()==null){
						result.getRs().setResult("");
					}
					if(!result.getRs().getResult().equals("")){
					Toast.makeText(W_WithDrawalActivity.this, result.getRs().getResult(), Toast.LENGTH_SHORT).show();
					}else{
						Toast.makeText(W_WithDrawalActivity.this, result.getMsg(), Toast.LENGTH_SHORT).show();	
					}
					}
				}else{
					Toast.makeText(W_WithDrawalActivity.this, "连接失败，未获取数据，", Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			public void exception() {
			}
		};
		task.execute();
	}

	private void sendBroadcast(String str) {
		Intent intent = new Intent();
		intent.setAction(SinoConstans.KEY_BalanceReceiver);
		intent.putExtra("Balance", str);
		sendBroadcast(intent);
	}

	public String getSystemTime() {
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");// 设置日期格式
		return df.format(new Date());// new Date()为获取当前系统时间}
	}

	@Override
	protected void onResume() {
		super.onResume();		

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			if(keyUtil!=null && keyUtil.getShowKeyboard()){
				keyUtil.hideKeyboard();
				return false;
			}
		}
		return super.onKeyDown(keyCode, event);
	}
	public class ChangeisPassReciver extends BroadcastReceiver {
		public    ChangeisPassReciver(){

		}

		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent.getAction().equals("com.sinoglobal.wallet.receiver.withdrawal")){
				int type = intent.getIntExtra("type",-1);
				if(type!=-1){
					if(type==101){
						String passWord = intent.getStringExtra("passWord");//设置密码成功后传来的数据
						str = withDrawal_num.getText().toString();
						getDynamicKey(passWord);
					}else if(type==201){
						getBankList();
					}else if(type==301){
						String isPass = intent.getStringExtra("isPass");//设置密码成功后传来的数据
						isHaspass=isPass;
					}
				}
			}

		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(changeisPassReciver);
	}
}
